import Vue from 'vue'
import Vuex from 'vuex'
import axios from './http'

Vue.use(Vuex)

const types = {
  SET_IS_AUTNENTIATED: 'SET_IS_AUTNENTIATED', // 是否认证通过
  SET_USER: 'SET_USER' // 用户信息
}

const state = { // 需要维护的状态
  isAutnenticated: false,  // 是否认证
  user: {},   // 存储用户信息
  userInfo: {},
  BASEURL: `http://192.168.2.166:5000/`,
  joinTopic: {}
}

const getters = {
  isAutnenticated: state => state.isAutnenticated,
  user: state => state.user
}

const mutations = {
  [ types.SET_IS_AUTNENTIATED ] (state, isAutnenticated) {
    if (isAutnenticated)
      state.isAutnenticated = isAutnenticated
    else
      state.isAutnenticated = false
  },
  [ types.SET_USER ] (state, user) {
    if (user) {
      state.user = user
    }
    else
      state.user = {}
  },
  getUserInfo (state, userInfo) {
    state.userInfo = userInfo
  },
  getJoinTopic (state, Topic) {
    state.joinTopic = Topic
  }
}

const actions = {
  setIsAutnenticated: ({ commit }, isAutnenticated) => {
    commit(types.SET_IS_AUTNENTIATED, isAutnenticated)
  },
  setUser: ({ commit }, user) => {
    commit(types.SET_USER, user)
  },
  clearCurrentState: ({ commit }) => {
    commit(types.SET_IS_AUTNENTIATED, false)
    commit(types.SET_USER, null)
  },
  setUserInfo ({ commit }, userId) {
    axios.get('/api/users/userInfo', { params: { id: userId } })
      .then(res => {
        let userInfo = res.data.data
        commit('getUserInfo', userInfo)
      })
      .catch((err) => {
        console.log(err);
      })
  }
}

export default new Vuex.Store({
  state,
  getters,
  mutations,
  actions
})
